package com.erdos.core.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.erdos.common.pagination.Page;
import com.erdos.common.web.BaseAction;
import com.erdos.core.constant.ReferenceConstant;
import com.erdos.core.entity.ContentText;
import com.erdos.core.service.ContentTextService;
import com.erdos.core.service.FieldDefinitionService;
import com.erdos.core.service.ReferenceService;

public class ContentTextAction extends BaseAction<ContentText> {
	
	 private static final Log logger = LogFactory.getLog(ContentTextAction.class);
	 private ContentTextService contentTextService;
	 private FieldDefinitionService fieldDefinitionService;
	 private ReferenceService referenceService ;
	 private List<ContentText> contentTexts=new ArrayList<ContentText>();
	 private boolean isUpdate=false;
	 private String contentId;
	 private Map<String,String> languageMap ;
	 
	 private String refreshDivID ;

	 
	 public String execute()
	 {
		 String res = "SUCCESS";
		 languageMap = this.referenceService.findRefValueMap(ReferenceConstant.REFERENCE_LANGUAGE) ;
		try {
			res = super.execute();
		} catch (Exception e) {
//			this.addActionError("初始化ContentText出错!");
		    this.addActionError(getText("tips.contenttext.init.haserror"));
		}
		 return res ;
	 }

	
/**
	 * 为页面准备必要数据
	 * @return
	 * @throws Exception
	 * @author jl
	 * @since  2008-7-22 
	 */
	public String input() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		if (StringUtils.isEmpty(this.contentId))  {
			this.contentId = request.getParameter("contentId");
		}
		
		languageMap = this.referenceService.findRefValueMap(ReferenceConstant.REFERENCE_LANGUAGE) ;
		
		if(StringUtils.isEmpty(contentId)){
			isUpdate=false;
		}
		else	{
			isUpdate=true;
			//从数据库中查询数据
			List<ContentText> oldcontentTexts=this.contentTextService.findByContentId(contentId);
			
			if(oldcontentTexts!=null && oldcontentTexts.size()>0){
				
				//先迭代LanguageMap 取出每个Language  再从oldContentTexts中取出此language对应的CotnentText放入contentTexts,
				//以保证languageMap与contentTexts中的数据一一对应,方便前台动态显示
				for(String key:languageMap.keySet()){
					//String language = languageMap.get(key) ;
					
					//标志位  判断此种语言language对应的ContentText是否存在 
					boolean isExistFlag = false ;
					
					for(ContentText contentText:oldcontentTexts) {
						
						//如果存在此种语言的ContentText 则放入contentTexts集合中 产跳出内层循环
						if(key.equals(contentText.getLanguage())) {
							isExistFlag = true ;
							contentTexts.add(contentText) ;
							break ;
						}
					}
					
					//如果不存在某种语言	新建一个实体并赋值
					if(isExistFlag == false){
						ContentText tempContentText = new ContentText() ;
						tempContentText.setContentId(contentId) ;
						tempContentText.setLanguage(languageMap.get(key)) ;
						contentTexts.add(tempContentText) ;
					}
				}
			}
		}
		return INPUT;
	}

	/**
     * 分页查询方法
     * @return
     * @throws Exception
     */
	@Override
    public String findByPage() throws Exception {
        HttpServletRequest request = ServletActionContext.getRequest();
        Map<String, Object> params=this.preparePageParams(request);
        Page<ContentText> page = getBaseService().findByPage(params, (Integer)params.get(PARAMS_KEY_PAGE_NO), (Integer)params.get(PARAMS_KEY_PAGE_LIMIT));
        entities = page.getResultList();
        request.setAttribute(PARAMS_KEY_PAGE_OBJECT, page);
        onFindByPage(request);
        languageMap = this.referenceService.findRefValueMap(ReferenceConstant.REFERENCE_LANGUAGE) ;
        return SUCCESS;
    }
	
	/**
	 * 按资源编码删除一组ContentText
	 * @return
	 * @throws Exception
	 * @author jl
	 * @since  2008-7-22 
	 */
	public String delete() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		String contentIdDelete = request.getParameter("contentId");
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("contentId", contentIdDelete);
		if(fieldDefinitionService.findByParams(params).size()>0) {
//			this.addActionError("该标签已被使用，无法删除");
			this.addActionError(getText("tips.delete.error"));
			this.input();
			return INPUT;
		}
		int deleteCount = contentTextService.deleteByContentId(contentIdDelete);
		request.setAttribute("method", "delete");
		saveBizMessage(getText("tips.delete.success", new String[]{String.valueOf(deleteCount)}));
		return SUCCESS;
	}

	/**
	 * 为编辑field页面生成列表
	 * @return
	 * @throws Exception
	 * @author shuwei
	 * @since  2008-7-21 
	 */
	public String findByPageForField() throws Exception {
		languageMap = this.referenceService.findRefValueMap(ReferenceConstant.REFERENCE_LANGUAGE) ;
		return super.findByPage();
	}
	
	/**
	 * 新增一组ContentText
	 * @return
	 * @throws Exception
	 * @author jl
	 * @since  2008-7-22 
	 */
	public String saveAll() throws Exception {
	    HttpServletRequest request = ServletActionContext.getRequest();
		String contentId=request.getParameter("contentId");
		String isUpdate=request.getParameter("isUpdate");
		if(!checkNull()) {
//			this.addActionError("标签不能全部为空");
		    this.addActionError(getText("tips.contenttext.add.hasValue"));
			return INPUT;
		}
		if(isUpdate.equals("true")){
			try {
			this.contentTextService.updateAll(contentTexts);
			} catch(Exception e) {
//				this.addActionError("出现错误，请稍后再试");
			    this.addActionError(getText("tips.contenttext.save.haserror"));
			    this.saveBizError(getText("tips.contenttext.save.haserror")) ;
			    return ERROR ;
			}
			request.setAttribute("method", "update");
			saveBizMessage(getText("tips.update.success", new String[] { String
						.valueOf(contentTexts.size()) }));
		}else{
			List<ContentText> insertList = new ArrayList<ContentText>();
			for(ContentText contentText:contentTexts) {
				contentText.setContentId(contentId);
				contentText.setVersion(Integer.valueOf(1)) ;
				if(!StringUtils.isEmpty(contentText.getContentText())) {
					insertList.add(contentText);
				}
			}
			try {
				this.contentTextService.insertAll(insertList);
			} catch(Exception e) {
//				this.addActionError("出现错误，请稍后再试");
			    this.addActionError(getText("tips.contenttext.save.haserror"));
			    this.saveBizError(getText("tips.contenttext.save.haserror")) ;
			    return ERROR ;
			}
			request.setAttribute("method", "insert");
			saveBizMessage(getText("tips.insert.success", new String[] { String
						.valueOf(contentTexts.size()) }));
		}
		return SUCCESS;
	 }

	/**
	 * 验证页面传回的Content_Text是否全部为空值
	 * @author jl
	 * @since  2008-7-22 
	 */
	private Boolean checkNull() {
		for(ContentText contentText:contentTexts) {
			if(!StringUtils.isEmpty(contentText.getContentText())) {
				return true;
			}	
		}
		return false;	
	}

	public ContentTextService getContentTextService() {
		return contentTextService;
	}
	
	public void setContentTextService(ContentTextService contentTextService) {
		this.contentTextService = contentTextService;
	}
	
	public List<ContentText> getContentTexts() {
		return contentTexts;
	}

	public void setContentTexts(List<ContentText> contentTexts) {
		this.contentTexts = contentTexts;
	}

	public String getContentId() {
		return contentId;
	}

	public void setContentId(String contentId) {
		this.contentId = contentId;
	}

	public boolean getIsUpdate() {
		return isUpdate;
	}

	public void setUpdate(boolean isUpdate) {
		this.isUpdate = isUpdate;
	}

	public FieldDefinitionService getFieldDefinitionService() {
		return fieldDefinitionService;
	}

	public void setFieldDefinitionService(
			FieldDefinitionService fieldDefinitionService) {
		this.fieldDefinitionService = fieldDefinitionService;
	}

	public String getRefreshDivID() {
		return refreshDivID;
	}


	public void setRefreshDivID(String refreshDivID) {
		this.refreshDivID = refreshDivID;
	}


	public ReferenceService getReferenceService() {
		return referenceService;
	}


	public void setReferenceService(ReferenceService referenceService) {
		this.referenceService = referenceService;
	}


	public Map<String, String> getLanguageMap() {
		return languageMap;
	}


	public void setLanguageMap(Map<String, String> languageMap) {
		this.languageMap = languageMap;
	}

}

